package com.powernode.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;

@Component
public class PowerTokenFilter implements GatewayFilter, Ordered {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 对于非认证登录的请求都需要进行token校验
     * 认证请求放行
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径
        String path = request.getPath().value();
        //判断是否为认证路径
        if(GatewayConstant.ALLOWED_PATHS.contains(path)){
            return chain.filter(exchange);
        }
        //其他的请求则获取请求头中token进行校验
        String token = request.getHeaders().getFirst(GatewayConstant.TOKEN_KEY);
        //校验
        if(StringUtils.hasText(token)&&stringRedisTemplate.hasKey(token)){
            return chain.filter(exchange);
        }
        //其他情况 响应错误提示信息
        ServerHttpResponse response = exchange.getResponse();
        //设置响应头
        response.getHeaders().add("content-type","application/json;charset=utf-8");
        //创建响应内容
        HashMap<String, Object> map = new HashMap<>();
        map.put("message","对不起，认证有误！");
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("success",false);
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer data = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(data));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
